package de.g18.it0a.jlaser.gui.view;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;

import de.g18.it0a.jlaser.domain.Room;
import de.g18.it0a.jlaser.domain.RoomConfiguration;
import de.g18.it0a.jlaser.domain.Tile;


public class RoomView {

    private final Room room;

    private BufferedImage image;
    private Graphics2D graphics;


    public RoomView(Room aRoom) {
        room = aRoom;
    }

    public BufferedImage render() {
        if (room == null) {
            return new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
        }

        image = new BufferedImage(room.getConfig().getWidth(),
                                  room.getConfig().getHeight(),
                                  BufferedImage.TYPE_INT_ARGB);
        graphics = image.createGraphics();
        paintRoom();
        graphics.dispose();
        flipImageVertical();
        return image;
    }

    private void paintRoom() {
        paintBackground();
        paintGrid();
        paintTiles();
    }

    private void paintBackground() {
        graphics.setColor(Color.LIGHT_GRAY);
        graphics.fillRect(0, 0, room.getConfig().getWidth(), room.getConfig().getHeight());
    }

    private void paintGrid() {
        graphics.setColor(Color.GRAY);
        for (int i = 0; i < room.getConfig().getWidth(); i += room.getConfig().getTileWidth()) {
            graphics.drawLine(i, 0, i, room.getConfig().getHeight());
        }
        for (int i = 0; i < room.getConfig().getHeight(); i += room.getConfig().getTileHeight()) {
            graphics.drawLine(0, i, room.getConfig().getWidth(), i);
        }
    }

    private void paintTiles() {
        graphics.setColor(Color.DARK_GRAY);
        for (Tile tile : room.getTiles()) {
            paintTile(room.getConfig(), tile);
        }
    }

    private void paintTile(RoomConfiguration aConfig, Tile aTile) {
        if (aTile.containsSolidFixtures()) {
            graphics.fillRect(aTile.getPosition().getX() + 1, aTile.getPosition().getY() + 1, 100, 100);
        }
    }

    public void flipImageVertical() {
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage dimg = new BufferedImage(width, height, image.getColorModel().getTransparency());
        Graphics2D g = dimg.createGraphics();
        g.drawImage(image, 0, 0, width, height, 0, height, width, 0, null);
        g.dispose();
        image = dimg;
    }
}
